package com.tsingteng.cosfun.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager;
import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLShortVideoComposer;
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.costar.BeforeFilmActivity;
import com.tsingteng.cosfun.ui.costar.CostarActivity;
import com.tsingteng.cosfun.ui.costar.ComposeVideoActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.Command;
import com.tsingteng.cosfun.utils.DesityUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.VideoOrderCommand;
import com.tsingteng.cosfun.utils.TimeUtils;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.CompletedView;
import com.tsingteng.cosfun.widget.PressImageView;

import org.litepal.util.LogUtil;


/**
 * 描述: 拖动页面
 * 创建人: 肖利
 * 时间: 2018/8/11
 * qq: (872179966)
 */

public class OrderVideoDialog implements View.OnClickListener {
    private static final String TAG = "OrderVideoDialog";
    private Activity context;
    private Dialog dialog;
    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private DragItemAdapter mDragItemAdapter;
    private PLShortVideoComposer mShortVideoComposer;
    private PressImageView repel;
    private PressImageView mIvNext;
    private boolean isShowSliceSelectDialog = true;
    private ProgressDialog progressDialog;
    private int type =-1;

    public OrderVideoDialog(Activity context,int type) {
        this.context = context;
        this.type = type;
        initView();
    }

    private void initView() {
//        //处理一下空白的视屏
//        VideoHelper.getIntence().clearEmptyVideoPath();
        dialog = new Dialog(context, R.style.dialog);
        dialog.setContentView(R.layout.dialog_order_video);
        mRecyclerView = dialog.findViewById(R.id.rv_order_rv);

        repel = dialog.findViewById(R.id.repel);
        mIvNext = dialog.findViewById(R.id.iv_next);
        repel.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        dialog.findViewById(R.id.iv_play).setOnClickListener(this);
        dialog.findViewById(R.id.iv_back).setOnClickListener(this);
        mLayoutManager = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mDragItemAdapter = new DragItemAdapter(VideoHelper.getIntence().getVideoSectionBeanList());
        mDragItemAdapter.setOnItemMovedListener(new DragItemAdapter.OnItemMovedListener() {
            @Override
            public void onMoveItem(int fromPosition, int toPosition) {
                try {
                    VideoOrderCommand videoOrderCommand = new VideoOrderCommand(fromPosition, toPosition);
                    VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoOrderCommand);
                }catch (NullPointerException e) {
                    LogUtil.d(TAG,e.getMessage());
                }
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (type == 1) {
                    ((CostarActivity) context).showSliceSelectDialog();
                }else {
                    ((BeforeFilmActivity) context).showSliceSelectDialog();
                }

            }
        });
        progressDialog = new ProgressDialog(context);
        RecyclerViewDragDropManager dragDropManager = new RecyclerViewDragDropManager();
        dragDropManager.setInitiateOnMove(false);
        dragDropManager.setInitiateOnLongPress(true);
        RecyclerView.Adapter adapter = dragDropManager.createWrappedAdapter(mDragItemAdapter);
        mRecyclerView.setAdapter(adapter);
        dragDropManager.attachRecyclerView(mRecyclerView);
        //拼接
        mShortVideoComposer = new PLShortVideoComposer(context);
    }


    public void show() {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setLayout(AppUtils.getScreenWidthAndHeight(context)[0] - DesityUtils.dp2px(30), ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    public void dissMiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.repel:
                Command undo = VideoHelper.getIntence().getCommendManger().undo();
                if (undo == null) {
                    AppUtils.showHintDialogToast(context, "撤销失败!");
                    return;
                }
                VideoHelper.getIntence().getOperationPosition(1, context, undo);
                refreshData();
                break;
            case R.id.iv_next:
                Command redo = VideoHelper.getIntence().getCommendManger().redo();
                if (redo == null) {
                    AppUtils.showHintDialogToast(context, "恢复失败!");
                    return;
                }
                VideoHelper.getIntence().getOperationPosition(2, context, redo);
                refreshData();
                break;
            case R.id.iv_play:
                toPlayToGether();
                break;

            case R.id.iv_back:
                dialog.dismiss();
                break;

        }
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        if (VideoHelper.getIntence().getCommendManger().isCanUndo()) {
            repel.setEnabled(true);
            repel.setImageDrawable(context.getResources().getDrawable(R.drawable.previous_black_icon));
        } else {
            repel.setEnabled(false);
            repel.setImageDrawable(context.getResources().getDrawable(R.drawable.previous_black_icon_nopress));
        }
        if (VideoHelper.getIntence().getCommendManger().isCanRedo()) {
            mIvNext.setEnabled(true);
            mIvNext.setImageDrawable(context.getResources().getDrawable(R.drawable.next_step_black_icon));
        } else {
            mIvNext.setEnabled(false);
            mIvNext.setImageDrawable(context.getResources().getDrawable(R.drawable.next_step_black_icon_nopress));
        }
        mDragItemAdapter.updatePaths(VideoHelper.getIntence().getVideoSectionBeanList());
        mDragItemAdapter.notifyDataSetChanged();
    }

    private void toPlayToGether() {
        VideoHelper.getIntence().clearEmptyVideoPath();
        if (VideoHelper.getIntence().getVideoPathList().size() <= 0) {
            new ContentDialog(context).setContent("请先添加一个视频片段!").setAffirmContent("我知道了!").setOnOneClickListener(new ContentDialog.OnOneClickListener() {
                @Override
                public void onAffirm() {

                }
            }).show();
            return;
        }

        onDone();
    }
    /**
     * 开始拼接
     */
    public void onDone() {
        if (VideoHelper.getIntence().getVideoPathList().size() <= 1) {
            Intent intent = new Intent(context, ComposeVideoActivity.class);
            intent.putExtra(VideoHelper.VIDEO_PATH, VideoHelper.getIntence().getVideoPathByIndex(0));
            context.startActivity(intent);
            context.overridePendingTransition(R.anim.activity_up, R.anim.activity_down);
        } else {
            PLAudioEncodeSetting plAudioEncodeSetting = new PLAudioEncodeSetting();
            PLVideoEncodeSetting setting = new PLVideoEncodeSetting(context);
            setting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_3);
            setting.setEncodingBitrate(VideoHelper.mEncodingBitrate);
            plAudioEncodeSetting.setHWCodecEnabled(true);
            if (mShortVideoComposer.composeVideos(VideoHelper.getIntence().getVideoPathList(), VideoHelper.VIDEO_COMPOSED + System.currentTimeMillis() + "compose.mp4", setting, mVideoSaveListener)) {
                if (progressDialog == null) progressDialog = new ProgressDialog(context);
                progressDialog.show();
                if (type == 1) {
                    ((CostarActivity) context).dissSliceSelectDialog();
                }else {
                    ((BeforeFilmActivity) context).dissSliceSelectDialog();
                }
            }


        }

    }


    private PLVideoSaveListener mVideoSaveListener = new PLVideoSaveListener() {
        @Override
        public void onSaveVideoSuccess(final String destFile) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(context, ComposeVideoActivity.class);
                    intent.putExtra(VideoHelper.VIDEO_PATH, destFile);
                    context.startActivity(intent);
                    context.overridePendingTransition(R.anim.activity_up, R.anim.activity_down);
                    dissMiss();
                    isShowSliceSelectDialog = true;
                    progressDialog.disMissDialog();
                }
            });
        }

        @Override
        public void onSaveVideoFailed(int errorCode) {
            progressDialog.disMissDialog();
        }

        @Override
        public void onSaveVideoCanceled() {
            progressDialog.disMissDialog();
        }


        @Override
        public void onProgressUpdate(final float percentage) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtils.i("onProgressUpdate" + percentage);
                    progressDialog.setmProgressbar((int) (100 * percentage));
                }
            });
        }
    };


}
